#include <47func.h>
int setNonblock(int fd){
    int status;//用来获取和设置fd的状态
    status = fcntl(fd,F_GETFL);//F_GETFL get flag
    status |= O_NONBLOCK;//在原来的属性基础上 增加非阻塞属性
    int ret = fcntl(fd,F_SETFL,status);//F_SETFL set flag 给已经打开的文件描述符修改属性
    ERROR_CHECK(ret,-1,"fcntl");
    return 0;
}
int main(int argc, char *argv[])
{
    // ./6_server 192.168.118.128 1234
    ARGS_CHECK(argc,3);
    int sockfd = socket(AF_INET,SOCK_STREAM,0);
    // AF_INET ipv4 SOCK_STREAM TCP
    struct sockaddr_in serverAddr;//带in 是ipv4地址 带in6是ipv6地址 不带是通用地址
    serverAddr.sin_family = AF_INET;//ipv4
    serverAddr.sin_addr.s_addr = inet_addr(argv[1]);//把点分十进制的ip地址转换成32位大端存储的地址
    serverAddr.sin_port = htons(atoi(argv[2]));//把端口用大端存储
    int ret = bind(sockfd,(struct sockaddr *)&serverAddr,sizeof(serverAddr));
    ERROR_CHECK(ret,-1,"bind");
    ret = listen(sockfd,10);
    ERROR_CHECK(ret,-1,"listen");
    struct sockaddr_in clientAddr;
    socklen_t clientAddrSize = sizeof(clientAddr);//一定要赋予初值
    int netfd = accept(sockfd,(struct sockaddr *)&clientAddr,&clientAddrSize);
    // sockfd专门用来建立连接 netfd负责和客户端的数据通信
    printf("addrlen = %d\n",clientAddrSize);
    printf("client sin_family = %d\n",clientAddr.sin_family);
    printf("client ip = %s\n", inet_ntoa(clientAddr.sin_addr));
    printf("client port =%d\n", ntohs(clientAddr.sin_port));
    
    //setNonblock(netfd);
    char buf[5] = {0};
    while(1){
        ssize_t sret = recv(netfd,buf,4,MSG_DONTWAIT);
        printf("sret = %ld, buf = %s\n", sret, buf);
        sleep(1);
        if(sret == -1){
            break;
        }
    }
    while(1){
        ssize_t sret =  recv(netfd,buf,4,0);
        printf("sret = %ld, buf = %s\n", sret, buf);
    }
    return 0;
}

